/**
 * request封装
 */
var constants = require('./constants.js');

function request(url, data = {}, method = 'GET') {
    return new Promise(function (resolve, reject) {
        let pages = getCurrentPages();
        let currentPage = pages[pages.length - 1].$vm;
        currentPage.setData({
            loading: true
        });
		
		var isToken = false;
		if (url.indexOf("/p/") >= 0 || url.indexOf("/u/") >= 0) {
			isToken = true;
		}
		
        uni.request({
            url: url,
            data: data,
            method: method,
			dataType: 'json',
			header: {
			    Authorization:  isToken ? uni.getStorageSync(constants.USER_TOKEN_KEY) : null,
			},
            success: function (res) {
                currentPage.setData({
                    loading: false
                });

                if (res.statusCode != 200) {
                    reject(res.errMsg);
                    return;
                }

                if (res.data.code == -1) {
                   
                    return;
                }

                resolve(res.data);
            },
            fail: function (err) {
                currentPage.setData({
                    loading: false
                });
                reject(err);
            }
        });
    });
}
/**
 * get请求
 */

function get(url, data = {}) {
    return request(url, data, 'GET');
}
/**
 * post请求
 */

function post(url, data = {}) {
    return request(url, data, 'POST');
}

module.exports = {
    get,
    post
};
